package master

import (
	"encoding/json"
	"gitee.com/zhengjianfeng/crontab-worker/common"
	"net"
	"net/http"
	"strconv"
	"time"
)

var (
	// 单例
	G_apiServer *ApiServer
)

// 任务的HTTP接口
type ApiServer struct {
	HttpServer *http.Server
}

func handleTesting(resp http.ResponseWriter, req *http.Request) {
	resp.Write([]byte("hello world"))
}

// 保存任务接口
func handleJobSave(resp http.ResponseWriter, req *http.Request) {

	var (
		bytes        []byte
		err          error
		postJob      string
		workerJob    common.WorkerJob
		oldWorkerJob *common.WorkerJob
	)

	// 1、解析POST表单
	if err = req.ParseForm(); err != nil {
		goto ERR
	}

	// 2、获取表单中的job字段
	postJob = req.PostForm.Get("job")

	// 3、反序列化
	if err = json.Unmarshal([]byte(postJob), &workerJob); err != nil {
		goto ERR
	}

	// 尝试解析任务，如果解析失败说明任务
	if err = G_workerJobParser.JobParser(workerJob); err != nil {
		goto ERR
	}

	// 保存到etcd中
	if oldWorkerJob, err = G_workerJobMgr.WorkerSaveJob(&workerJob); err != nil {
		goto ERR
	}

	// 返回正常应答{"errno":0,"msg":"success","data":{...}}
	if bytes, err = common.BuildResponse(0, "success", oldWorkerJob); err != nil {
		goto ERR
	}

	resp.Write(bytes)
	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
	return
}

// 初始化事务
func InitApiServer() (err error) {

	var (
		mux        *http.ServeMux
		httpServer *http.Server
		listener   net.Listener
	)

	// 路由配置
	mux = http.NewServeMux()
	mux.HandleFunc("/", handleTesting)
	mux.HandleFunc("/worker/job/save", handleJobSave)

	// 启动一个HTTP服务
	httpServer = &http.Server{
		ReadHeaderTimeout: time.Duration(G_config.ApiReadTimeout) * time.Millisecond,
		WriteTimeout:      time.Duration(G_config.ApiWriteTimeout) * time.Millisecond,
		Handler:           mux,
	}

	// 启动TCP监听
	if listener, err = net.Listen("tcp", ":"+strconv.Itoa(G_config.ApiPort)); err != nil {
		return
	}

	// 赋值单例
	G_apiServer = &ApiServer{
		HttpServer: httpServer,
	}

	// 启动服务
	go httpServer.Serve(listener)

	return
}
